//
//  WBNetworkManager+Extension.swift
//  WinsonWeibo
//
//  Created by Administrator on 2017/4/15.
//  Copyright © 2017年 Winson. All rights reserved.
//

import Foundation


// MARK: - 封装新浪微博的网络请求方法
extension WBNetworkManager {

    /// 添加微博数据字典数组
    ///
    /// - Parameters:
    ///   - since_id: 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0
    /// - Parameter completion: 完成回调[list： 微博字典数组／是否成功]
    func statusList(since_id:Int64 = 0, max_id: Int64 = 0, completion: @escaping(_ list: [[String:Any]]?, _ isSuccess: Bool)->()) {

        let URLString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let paramers = ["since_id":"\(since_id)",
            "max_id":"\(max_id > 0 ? (max_id - 1) : 0)"]

        tokenRequest(URLString: URLString, paramers: paramers) { (json, isSuccess) in
            // 从json中获取 statuses 字典数组/ 如果as？ 失败， list = nil
            let josnDict = json as? [String: Any]
            let list = josnDict?["statuses"] as? [[String: Any]]
            completion(list, isSuccess)
        }
    }

    /// 获取未读微博的数量
    ///
    /// - Parameter completion: 完成回调[count: 未读微博的条数]
    func unreadCount(completion: @escaping(_ count: Int)->()) {

        guard let uid = userAccount.uid else {
            return
        }

        let URLString = "https://rm.api.weibo.com/2/remind/unread_count.json"

        let paramers = ["uid":uid]

        tokenRequest(URLString: URLString, paramers: paramers) { (json, isSuccess) in

            let dict = json as? [String: Any]

            let count = dict?["status"] as? Int
            completion(count ?? 0)
        }
    }
}

// MARK: -获取用户的用户名和图像
extension WBNetworkManager {
    /// 加载用户信息 - 用户登录后立即执行
    fileprivate func loadUserInfo(completion:@escaping (_ dict:[String:Any])->()) {

        guard let uid = userAccount.uid else {
            return
        }

        let URLString = "https://api.weibo.com/2/users/show.json"

        let paramers = ["uid":uid]

        tokenRequest(URLString: URLString, paramers: paramers) { (json, isSuccess) in
            completion((json as? [String:Any]) ?? [:])
        }
    }
}

// MARK: - OAuth 相关方法
extension WBNetworkManager {

    /// 加载token
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 完成回调
    func loadAccessToken(code: String, completion: @escaping(_ isSuccess: Bool)->()) {

        let urlString = "https://api.weibo.com/oauth2/access_token"

        let params = ["client_id": WBAppKey,
                      "client_secret": WBAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": WBRedirectURI]
        // 发起网络请求
        request(method: WBHTTPMethod.POST, URLString: urlString, paramers: params) { (json, isSuccess) in

            // 设置用户的登录信息
            self.userAccount.yy_modelSet(withJSON: json ?? [])

            print(self.userAccount)

            // 加载用户信息
            self.loadUserInfo(completion: { (dict) in

                // 设置用户个人信息
                self.userAccount.yy_modelSet(with: dict)
                print(self.userAccount)

                // 保存 用户信息
                self.userAccount.saveUserAccount()
                
                // 设置回调
                completion(isSuccess)
            })
        }
    }
}
